package com.zxj.friend.service.exam.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zxj.common.core.contains.Constants;
import com.zxj.common.core.domain.R;
import com.zxj.common.core.domain.vo.PageVO;
import com.zxj.common.core.enums.ExamListType;
import com.zxj.common.core.enums.ExamStatusEnum;
import com.zxj.common.core.utils.ThreadLocalUtil;
import com.zxj.friend.domain.exam.dto.ExamQueryPageDTO;
import com.zxj.friend.domain.exam.dto.ExamRankDTO;
import com.zxj.friend.domain.exam.entity.Exam;
import com.zxj.friend.domain.exam.vo.ExamRankVO;
import com.zxj.friend.domain.exam.vo.ExamVO;
import com.zxj.friend.domain.user.vo.UserVO;
import com.zxj.friend.manager.ExamCacheManager;
import com.zxj.friend.manager.UserCacheManager;
import com.zxj.friend.mapper.exam.ExamMapper;
import com.zxj.friend.mapper.user.UserExamMapper;
import com.zxj.friend.service.exam.IExamService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 竞赛表结构 服务实现类
 * </p>
 *
 * @author zxj2022
 * @since 2024-12-29
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements IExamService {


    private final ExamCacheManager examCacheManager;

    private final UserExamMapper userExamMapper;

    private final UserCacheManager userCacheManager;


    /**
     * 数据库版: 分页查询竞赛列表
     * @param examQueryPageDTO 查询条件
     * @return
     */
    @Override
    public PageVO<ExamVO> pageQuery(ExamQueryPageDTO examQueryPageDTO) {
        PageHelper.startPage(examQueryPageDTO.getPageNo(), examQueryPageDTO.getPageSize());
        List<Exam> list = this.lambdaQuery()
                .eq(Exam::getStatus, ExamStatusEnum.PUBLISHED.getValue()) // 竞赛状态为已发布
                .like(examQueryPageDTO.getTitle() != null, Exam::getTitle, examQueryPageDTO.getTitle()) // 竞赛标题进行模糊查询
                .ge(examQueryPageDTO.getStartTime() != null, Exam::getStartTime, examQueryPageDTO.getStartTime()) // 竞赛开始时间大于等于查询开始时间
                .le(examQueryPageDTO.getEndTime() != null, Exam::getEndTime, examQueryPageDTO.getEndTime()) // 竞赛结束时间小于等于查询结束时间
                .gt(ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examQueryPageDTO.getType()), Exam::getEndTime, LocalDateTime.now()) // 竞赛类型为未结束的，结束时间大于当前时间
                .le(ExamListType.EXAM_HISTORY_LIST.getValue().equals(examQueryPageDTO.getType()), Exam::getEndTime, LocalDateTime.now()) // 竞赛类型为历史的，结束时间小于当前时间
                .orderByDesc(Exam::getCreateTime) // 按照开始时间倒序
                .list();
        List<ExamVO> examVOS = BeanUtil.copyToList(list, ExamVO.class);
        return PageVO.of(examVOS);
    }

    /**
     * redis版: 分页查询竞赛列表
     * @param examQueryPageDTO 查询条件
     * @return 竞赛列表
     */
    @Override
    public PageVO<ExamVO> redisList(ExamQueryPageDTO examQueryPageDTO) {
        // 如果查询条件中有开始时间、结束时间或者标题，直接查询数据库
        if (StrUtil.isNotBlank(examQueryPageDTO.getStartTime()) || StrUtil.isNotBlank(examQueryPageDTO.getEndTime()) || StrUtil.isNotBlank(examQueryPageDTO.getTitle())) {
            List<ExamVO> examVOList = examCacheManager.getExamVOListByCondition(examQueryPageDTO);
            if (CollectionUtil.isEmpty(examVOList)) {
                return PageVO.empty();
            }
            Long total = examCacheManager.getListSize(examQueryPageDTO);
            return PageVO.of(examVOList, total);
        }

        //从redis当中获取  竞赛列表的数据
        // 1. 获取对应类型的竞赛列表大小 - 这一步是为了判断是否要查询数据库
        Long total = examCacheManager.getListSize(examQueryPageDTO.getType());
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            // 2. 如果redis中没有数据，从数据库中查询数据并且刷新缓存
            examVOList = pageQuery(examQueryPageDTO).getList();
            examCacheManager.refreshCache(examQueryPageDTO.getType());
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            // 3. 如果redis中有数据，直接从redis中获取数据
            examVOList = examCacheManager.getExamVOList(examQueryPageDTO);
            // 4. 重新获取对应类型的竞赛列表大小 - 这是因为可能在刷新缓存的时候，数据有变化
            total = examCacheManager.getListSize(examQueryPageDTO.getType());
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return PageVO.empty();
        }
        this.assembleExamVOList(examVOList);
        return PageVO.of(examVOList, total);
    }

    /**
     * 获取竞赛中的第一题
     * @param examId 竞赛ID
     * @return 第一题的ID
     */
    @Override
    public String getFirstQuestion(Long examId) {
        checkAndRefresh(examId);
        return examCacheManager.getFirstQuestion(examId).toString();
    }

    /**
     * 获取竞赛上一题ID
     * @param examId 竞赛ID
     * @param questionId 题目ID
     * @return 上一题的ID
     */
    @Override
    public String preQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.preQuestion(examId, questionId).toString();
    }

    /**
     * 获取竞赛下一题ID
     * @param examId 竞赛ID
     * @param questionId 题目ID
     * @return 下一题的ID
     */
    @Override
    public String nextQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.nextQuestion(examId, questionId).toString();
    }


    private void assembleExamVOList(List<ExamVO> examVOList) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
        if (CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for (ExamVO examVO : examVOList) {
            if (userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }

    /**
     * 查询竞赛排行榜
     * @param examRankDTO 查询条件
     * @return 竞赛排行榜
     */
    @Override
    public PageVO<ExamRankVO> rankList(ExamRankDTO examRankDTO) {
        Long total = examCacheManager.getRankListSize(examRankDTO.getExamId());
        List<ExamRankVO> examRankVOList;
        if (total == null || total <= 0) {
            PageHelper.startPage(examRankDTO.getPageNo(), examRankDTO.getPageSize());
            examRankVOList = userExamMapper.selectExamRankList(examRankDTO.getExamId());
            examCacheManager.refreshExamRankCache(examRankDTO.getExamId());
            total = new PageInfo<>(examRankVOList).getTotal();
        } else {
            examRankVOList = examCacheManager.getExamRankList(examRankDTO);
        }
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return PageVO.empty();
        }
        assembleExamRankVOList(examRankVOList);
        return PageVO.of(examRankVOList, total);
    }

    /**
     * 检查并刷新缓存
     * @param examId 竞赛ID
     */
    private void checkAndRefresh(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
    }

    /**
     * 组装竞赛排行榜
     * @param examRankVOList 竞赛排行榜
     */
    private void assembleExamRankVOList(List<ExamRankVO> examRankVOList) {
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return;
        }
        for (ExamRankVO examRankVO : examRankVOList) {
            Long userId = examRankVO.getUserId();

            UserVO user = userCacheManager.getUserById(userId);
            examRankVO.setNickName(user.getNickName());
        }
    }
}
